import { GameConfig } from "../configs/GameConfig";
import { ILotteryElement } from "../configs/Lottery";
import { ILotteryEntryElement } from "../configs/LotteryEntry";
import { Attribute } from "../etc/Attribute";
import { UIPool } from "../etc/UIPool";
import { util } from "../etc/Util";
import { LotteryModuleC } from "../module/LotteryModule";
import { PlayerModuleC } from "../module/PlayerModule";
import LotteryItem_Generate from "../ui-generate/LotteryItem_generate";
import LotteryWindow_Generate from "../ui-generate/LotteryWindow_generate";
import { Notice } from "./Notice";

export class LotteryWindow extends LotteryWindow_Generate{
    private entryCfg:ILotteryEntryElement
    private itemPool:UIPool<LotteryItem>
    private playerMD:PlayerModuleC

    onStart(){
        this.playerMD = ModuleService.getModule(PlayerModuleC)

        this.btn_close.onClicked.add(()=>{
            UIService.hideUI(this)
        })

        this.itemPool = new UIPool(()=>{
            let item = UIService.create(LotteryItem)
            this.con_items.addChild(item.uiObject)
            return item
        })

        this.btn_draw.onClicked.add(this.onDrawClicked.bind(this))
    }
    
    setInfo(entryCfgID:number){
        this.entryCfg = GameConfig.LotteryEntry.getElement(entryCfgID)
        this.itemPool.resetAll()
        for (const cfg of GameConfig.Lottery.getAllElement()) {
            if(cfg.Type != this.entryCfg.Type) continue
            
            let item = this.itemPool.get()
            item.setInfo(cfg)
        }
        this.txt_cost.text = `*${this.entryCfg.CostMoney}`
    }

    private onDrawClicked(){
        let have = this.playerMD.getAttr(Attribute.EnumAttributeType.money)
        if(have < this.entryCfg.CostMoney) {
            Notice.showTopNotice('材料不足!')
            return
        }
        ModuleService.getModule(LotteryModuleC).send_draw_request(this.entryCfg.ID)
    }
}

export class LotteryItem extends LotteryItem_Generate{
    private lotteryCfg:ILotteryElement

    setInfo(cfg:ILotteryElement){
        this.lotteryCfg = cfg
    
        if(this.lotteryCfg.IsItem){
            let itemCfg = GameConfig.Item.getElement(this.lotteryCfg.RewardID)
            this.txt_name.text = itemCfg.Name
            if(itemCfg.IconIsAssetsIcon){
                util.loadAssetsIcon(itemCfg.Icon, this.img_icon)
            }else{
                this.img_icon.imageGuid = itemCfg.Icon
            }
        }

        this.txt_random_factor.text = `概率:${this.lotteryCfg.RandomFactor * 100}%`
    }
}